const executeSql = require("../utils/query");

exports.getTagPage = async (
    page,
    pageSize,
    tag_name,
    is_show
) => {

    let offset = (page - 1) * pageSize

    let sql = `select * from tag where 1 `

    //  根据查询条件，有传条件，动态的拼接sql语句
    if (tag_name) {
        sql += ` and tag_name like '%${tag_name}%'`
    }
    if (is_show) {
        sql += ` and is_show = ${is_show}`
    }
    sql += ` order by tag_id limit ${offset},${pageSize}`

    return await executeSql(sql)
}

exports.getALlTagCount = async (
                                    tag_name,
                                    is_show
                                ) => {
    console.log('2222  '+tag_name,'2222 '+is_show)


    let sql = `select count(*) as count from tag where 1 `
    //  根据查询条件，有传条件，动态的拼接sql语句
    if (tag_name) {
        sql += ` and tag_name like '%${tag_name}%'`
    }
    if (is_show) {
        sql += ` and is_show = ${is_show}`
    }
    let result = await executeSql(sql)

    return result[0].count
}

exports.delTagById = async (tag_id = 0) => {
    console.log(tag_id)
    let sql = `delete from tag where tag_id = ${tag_id}`
    return await executeSql(sql)
}

exports.delBatchTag = async (tag_ids) => {
    let sql = `delete from tag where tag_id in (${tag_ids})`
    return await executeSql(sql)
}

exports.checkAddTagName = async (tag_name) => {
    let sql = `select * from tag where tag_name = '${tag_name}'`

    let result = await executeSql(sql)

    if (result.length > 0) {
        // 有重复
        return false
    }
    return true
}

exports.insertTag = async (data) => {
    let {tag_name, is_show} = data
    let sql = `insert into tag(tag_name, is_show) values('${tag_name}', ${is_show})`
    return await executeSql(sql)
}

exports.checkUpdateTagName = async (tag_id, tag_name) => {
    let sql = `select tag_id from tag where tag_name = '${tag_name}' and tag_id != ${tag_id}`

    let result = await executeSql(sql)

    if (result.length > 0) {
        // 有重复
        return false
    }
    return true
}

exports.updateTag = async (data) => {
    let {tag_id, tag_name,is_show} = data
    let sql = `update tag set tag_name = '${tag_name}',is_show = ${is_show} where tag_id = ${tag_id};`
    return await executeSql(sql)
}

exports.getAllTags = async () => {
    let sql = 'select * from tag'
    return await executeSql(sql)
}